package com.google.code.stalkernet.advertisement;

import java.net.SocketAddress;

import com.google.code.stalkernet.node.NodeID;

/**
 * Contains various useful method to work wiht advertisements.
 *
 * @author Mikhail Vladimirov
 */
public class AdvertisementUtils
{
    private AdvertisementUtils ()
    {
        throw new Error ("Do not instantiate me");
    }

    /**
     * Create new advertisement with given node address and ID.
     *
     * @param socketAddress node address
     * @param nodeID node ID
     * @return {@link Advertisement} object
     */
    public static Advertisement createAdvertisement (
        SocketAddress socketAddress, NodeID nodeID)
    {
        if (socketAddress == null)
            throw new IllegalArgumentException ("Socket address is null");

        if (nodeID == null)
            throw new IllegalArgumentException ("Node ID is null");

        return new MyAdvertisement (socketAddress, nodeID);
    }

    /**
     * Format advertisement as human-readable string.
     *
     * @param advertisement advertisement to format
     * @return human-readable representation of given advertisement
     */
    public static String formatAdvertisement (Advertisement advertisement)
    {
        if (advertisement == null)
            throw new IllegalArgumentException ("Advertisement is null");

        return advertisement.getNodeID () + "@" +
            advertisement.getSocketAddress ();
    }

    private static class MyAdvertisement extends AbstractAdvertisement
    {
        private final SocketAddress socketAddress;
        private final NodeID nodeID;

        public MyAdvertisement (
            SocketAddress socketAddress, NodeID nodeID)
        {
            if (socketAddress == null)
                throw new IllegalArgumentException ("Socket address is null");

            if (nodeID == null)
                throw new IllegalArgumentException ("Node ID is null");

            this.socketAddress = socketAddress;
            this.nodeID = nodeID;
        }

        @Override
        public SocketAddress getSocketAddress ()
        {
            return socketAddress;
        }

        @Override
        public NodeID getNodeID ()
        {
            return nodeID;
        }
    }
}
